package com.shwread.android.qysw;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;
import com.shwread.android.qysw10000152.R;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import logic.bean.AppInfo;
import logic.util.AppUtils;
import logic.util.FileUtil;
import logic.util.Util;


public class UpdateApkService
        extends
        Service
{
	public static final String  UPDATEURL       = "UPDATE_URL";
	
	public static final String  UPDATE_APK      = "android.intent.action.updateapk";
	public static final String  UPDATE_APK_FILE = "updateApkFile";
	public static final String  UPDATE_APK_ID   = "updateApkId";
	private int                 UpdateNotifId   = 1011;
	
	private long                startTime       = 0;
	private long                currTime        = 0;
	private static AppInfo      appInfo;
	private NotificationManager notifiManager;
	private Notification        notif;
	private static String       filePath;
	public static int           currentNum;
	
	public static void setURL(AppInfo ver, String path) {
		appInfo = ver;
		filePath = path;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		if (appInfo != null)
		{
			if (!Util.isEmpty(appInfo.fileUrl))
			{
				Log.d("update", "start update Service!");
				Log.d("update", "update_url:" + appInfo.fileUrl);
				Thread th = new Thread(new Runnable()
				{
					
					@Override
					public void run() {
						downLoadApk(UpdateApkService.this, appInfo.fileUrl);
					}
				});
				th.start();
			}
		}
	}
	
	private void downLoadApk(Context context, String url) {
		
		InputStream is = null;
		FileOutputStream fos = null;
		File myTempFile = null;
		try
		{
			URL myURL = new URL(url);
			URLConnection conn;
			conn = myURL.openConnection();
			conn.connect();
			is = conn.getInputStream();
			if (is == null) { throw new Exception("stream is null"); }
			
			myTempFile = new File(filePath);
			fos = new FileOutputStream(myTempFile);
			int total = conn.getContentLength();
			Log.d("update", "download total" + total);
			int curr = 0;
			startTime = System.currentTimeMillis();
			byte buf[] = new byte[102400];
			do
			{
				currTime = System.currentTimeMillis();
				int numread = is.read(buf);
				curr = curr + numread;
				int num = curr * 100 / total;
				currentNum = num;
				if ((currTime - startTime > 1000))
				{
					startTime = currTime;
					NotifBar(num);
				}
				if (numread <= 0)
				{
					break;
				}
				fos.write(buf, 0, numread);
			}
			while (true);
			NotifBar(myTempFile);
		}
		catch (Exception e)
		{
			e.printStackTrace();
//			NotifBar();
			downError();
			Log.e("update", "update error");
		}
	}
	
	private void downError() {
		if (notifiManager == null)
		{
			notifiManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
		}
		if (notif == null)
		{
			notif = new Notification(R.drawable.ic_launcher, this.getString(R.string.str_downloading), System.currentTimeMillis());
			RemoteViews contentView = new RemoteViews(this.getPackageName(), R.layout.update_version_noti);
			notif.contentView = contentView;
			notif.flags = Notification.FLAG_AUTO_CANCEL;
			Intent intent = new Intent();
			PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
			notif.contentIntent = pendingIntent;
		}
		
		notif.contentView.setTextViewText(R.id.content_view_text1, "下载失败");
		notifiManager.notify(UpdateNotifId, notif);
		System.out.println("下载失败！！！！"+filePath);
		if(FileUtil.exists(filePath)){
			FileUtil.delFile(filePath);
		}
	}
	private void NotifBar(int num) {
		if (notifiManager == null)
		{
			notifiManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
		}
		if (notif == null)
		{
			notif = new Notification(R.drawable.ic_launcher, this.getString(R.string.str_downloading), System.currentTimeMillis());
			RemoteViews contentView = new RemoteViews(this.getPackageName(), R.layout.update_version_noti);
			notif.contentView = contentView;
			notif.flags = Notification.FLAG_AUTO_CANCEL;
			Intent intent = new Intent();
			PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
			notif.contentIntent = pendingIntent;
		}
		
		notif.contentView.setProgressBar(R.id.content_view_progress, 100, num, false);
		notif.contentView.setTextViewText(R.id.content_view_text1, this.getString(R.string.str_downloading) + num + "%");
		notifiManager.notify(UpdateNotifId, notif);
	}
	
	private void NotifBar(File myTempFile) {
		if (notifiManager == null)
		{
			notifiManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
		}
		notifiManager.cancel(UpdateNotifId);
		if (notif != null)
		{
			notif = null;
		}
		
		notifiManager.cancel(UpdateNotifId);
		
		sendBroadcast(filePath);
	}
	
	private void NotifBar() {
		if (notifiManager == null)
		{
			notifiManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
		}
		notifiManager.cancel(UpdateNotifId);
		if (notif != null)
		{
			notif = null;
		}
		notif = new Notification(R.drawable.ic_launcher, this.getString(R.string.downloadfail), System.currentTimeMillis());
		notif.contentView = new RemoteViews(this.getPackageName(), R.layout.update_version_noti);
		notif.contentView.setProgressBar(R.id.content_view_progress, 100, 0, true);
		notif.flags = Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL;
		Intent intent = new Intent();
		intent.setClass(this, UpdateApkService.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
		notif.setLatestEventInfo(this, this.getString(R.string.downloadfail), this.getString(R.string.tryAgain), pendingIntent);
		notifiManager.notify(UpdateNotifId, notif);
		
		//		String filePath = "";
		//		sendBroadcast(filePath);
	}
	
	private void sendBroadcast(String filePath) {
		Intent intentUpdateBroadcast = new Intent();
		intentUpdateBroadcast.putExtra("packageName", AppUtils.getPackageName(this));
		intentUpdateBroadcast.setAction(UPDATE_APK);
		if (!Util.isEmpty(filePath))
		{
			intentUpdateBroadcast.putExtra(UPDATE_APK_FILE, filePath);
			//			intentUpdateBroadcast.putExtra(UPDATE_APK_ID, UpdateNotifId);
		}
		this.sendBroadcast(intentUpdateBroadcast);
		Log.d("updateAPK", "have send broadcast!");
	}
	
	private static NotificationManager MMnotifiManager = null;
	private static Notification        MMnotif         = null;
	static int                         MMUpdateNotifId = 1;
	
	public static void NotifDownMMBar(Context context, int num) {
		
		if (MMnotifiManager == null)
		{
			MMnotifiManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
		}
		if (MMnotif == null)
		{
			MMnotif = new Notification(R.drawable.ic_launcher, context.getString(R.string.str_downloading), System.currentTimeMillis());
			RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.update_version_noti);
			contentView.setProgressBar(R.id.content_view_progress, 100, 0, false);
			contentView.setTextViewText(R.id.content_view_text1, context.getString(R.string.str_downloading) + "0%");
			MMnotif.contentView = contentView;
			MMnotif.flags = Notification.FLAG_ONLY_ALERT_ONCE;
			Intent intent = new Intent();
			PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
			MMnotif.contentIntent = pendingIntent;
		}
		else
		{
			MMnotif.contentView.setProgressBar(R.id.content_view_progress, 100, num, false);
			MMnotif.contentView.setTextViewText(R.id.content_view_text1, context.getString(R.string.str_downloading) + num + "%");
		}
		MMnotifiManager.notify(MMUpdateNotifId, MMnotif);
	}
	
	public static void RemoveNotifMMBar() {
		if (MMnotifiManager != null) MMnotifiManager.cancel(MMUpdateNotifId);
	}
}
